package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池初始化
 */

//目的：创建一个全局共享的线程池，用于异步处理耗时任务
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor init() {

        int cpuCount = Runtime.getRuntime().availableProcessors();
        //核心线程数  最大线程数  空闲线程存活时间  时间单位  任务队列(有界阻塞队列) 线程工厂  拒绝策略
        //核心线程数和最大线程数一般设置相同避免来回伸缩 cpu核数*2居多或者+1个
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                cpuCount + 1,
                cpuCount * 2,
                0,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(100),
                Executors.defaultThreadFactory(),
                (runnable, executor) -> {
                    System.out.println(" 线程池达到了最大饱和... ");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    //再次将拒绝任务提交给线程池执行
                    executor.submit(runnable);
                }
        );
        //threadPoolExecutor.prestartAllCoreThreads(); //初始化所有核心线程数
        threadPoolExecutor.prestartCoreThread(); //初始化1个核心线程数

        //threadPoolExecutor.shutdown();
        return threadPoolExecutor;
    }

}
